package Flap::App::Cmd;
use Flap qw/-b Flap::App -i Flap::App::Web -m -s -w/;

sub args { shift->{args} }

sub argv { @{shift->{argv}} }

sub default_config { shift->project->config->App->Cmd }

sub dispatch {
    my($c, $path, $opt) = (shift, shift, shift || {});
    
    $path =~ /^(?:(.+)::)?(\w+)\z/ || die qq{No route for: "$path"};
    my $r = {controller => $1 || 'Root', action => $2};
    local $c->{route} = $r;
    $c->_dispatch($r, $opt);
}

sub log { shift->_log('[O]', @_) }

sub _log {
    my $c = shift;
    print STDERR "$_[0] $_[1]";
}

sub new {
    my $c = shift->_new_({});
    $c->{path} = shift || die 'No path';
    $c->{pid}  = $$;
    $c->{argv} = [@_];
    $c->{args} = {};
    while(my $argv = shift){
        if($argv =~ /^-(\w+)\z/){
            my @o = split(//, "$1");
            $c->{args}{"-$_"} = [] for @o;
            $argv = $c->{args}{"-$o[-1]"};
        }elsif($argv =~ /^(--.+)\z/){
            $argv = $c->{args}{$1} = [];
        }else{
            $c->{args}{$1} = $2 if $argv =~ /^(\w+)=(.+)\z/;
            next;
        }
        push @$argv, shift while @_ && $_[0] !~ /^-/;
    }
    $c;
}

sub project_options {
    my $c = shift;
    return {trace => {warn => sub{ $c->_log('[!]', @_) }}};
}

sub run {
    my $class = shift;
    $class->project->begin($class->project_options);
    my $c = $class->new(@_);
    eval{ $c->dispatch($c->path) };
    $c->_log('[X]', $@) if $@;
    
    if($c->{pid} eq $$){
    }
}

1;
